#include "class_tick.h"

class_tick::class_tick(){}
class_tick::~class_tick(){}

//读入
int class_tick::read(const std::filesystem::path &dz,int len)
{
	int num = 0;
	struct_tick tick;
memset(&tick, 0, sizeof(struct_tick));
std::ifstream wj(dz.c_str(), std::ios::binary | std::ios::ate | std::ios::in);

if(!wj.is_open() )
{
std::cout<<dz<<"打开失败"<<std::endl;
return -1;
}

std::streampos len1 = wj.tellg(),len2=len1;
if (len * sizeof(struct_tick) <len1)
{
len2 -= len * sizeof(struct_tick);
}
else {
len2 = 0;
}
wj.seekg(len2);

while (wj.tellg() + static_cast<std::streamoff>(sizeof(struct_tick)) < len1)
{
wj.read(reinterpret_cast<char *>(&tick), sizeof(struct_tick));

if(wj.fail() )
{
wj.clear();
std::cout<<dz<<"读取失败"<<std::endl;
break;
}

if(tick.UpdateTime[2] != ':' || tick.UpdateTime[5] != ':' )
{
len2 += 1;
wj.seekg(len2);
continue;
}
len2 += sizeof(struct_tick);
wj.seekg(len2);

std::lock_guard<std::mutex> g(mutex0);
datas.push_back(tick);
num++;
}
wj.clear();
wj.close();
return num;
}

//写出
int class_tick::write(std::string dz,int len)
{
	int num = 0;
	if(datas.size() == 0)
{
return 0;
}

std::fstream wj;//声明写文件
wj.open(dz.c_str(), std::ios::app | std::ios::binary | std::ios::out);

if(!wj.is_open() )
{
	std::cout<<dz<<"打开失败"<<std::endl;
return -1;
}

for(int i=0;i<len;++i)
{
	struct_tick tmp;
	{
		std::lock_guard<std::mutex> g(mutex0);
		if (datas.empty()) break;
		tmp = datas.front();
		datas.pop_front();
	}
	wj.write(reinterpret_cast<const char*>(&tmp), sizeof(tmp));
	wj.flush();   // 立即刷内核缓冲
	num++;
}
wj.close();
datas.shrink_to_fit();

return num;
}

//插入
void class_tick::insert(CThostFtdcDepthMarketDataField data)
{

struct_tick tick;

tick.LastPrice = data.LastPrice;
tick.BidPrice1=data.BidPrice1;
tick.AskPrice1=data.AskPrice1;
tick.OpenInterest=data.OpenInterest;
tick.Volume=data.Volume;
tick.BidVolume1=data.BidVolume1;
tick.AskVolume1=data.AskVolume1;
tick.UpdateMillisec=data.UpdateMillisec;
memcpy(tick.TradingDay,data.TradingDay, sizeof(tick.TradingDay) - 1);
tick.TradingDay[sizeof(tick.TradingDay)-1] = '\0';
memcpy(tick.UpdateTime,data.UpdateTime, sizeof(tick.UpdateTime) - 1);
tick.UpdateTime[sizeof(tick.UpdateTime) - 1] = '\0';

std::lock_guard<std::mutex> g(mutex0);
datas.push_back(tick);

return;
}
